﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CommunityServerRest;
using CSWriter.Properties;
using CSWriter.Blogs;
using System.Web;

namespace CSWriter {
	public partial class OnlineManager : Form {

		private BlogManager Manager { get; set; }
		public BlogPost SelectedPost { get; set; }

		public OnlineManager(BlogManager manager) {
			InitializeComponent();

			Manager = manager;
		}

		private void listView1_SelectedIndexChanged(object sender, EventArgs e) {
			if (listView1.SelectedIndices.Count > 0) {
				selectMenu.Enabled = true;
				listView1.ContextMenu = contextMenu1;
			} else {
				selectMenu.Enabled = false;
				listView1.ContextMenu = null;
			}
		}

		private void listView1_ItemActivate(object sender, EventArgs e) {

			SelectedPost = GetSelectedPost();
			DialogResult = DialogResult.OK;
			Close();
		}

		private void ViewMorePosts_Load(object sender, EventArgs e) {
			

			Cursor.Current = Cursors.WaitCursor;
			try {
				BlogPostList list = Manager.GetRecentPosts(20);
				listView1.BeginUpdate();
				foreach (BlogPost post in list.blogPosts) {
					ListViewItem item = new ListViewItem();
					item.Text = string.Concat(post.Title, " - ", string.Format(Resources.Views, post.Views));
					item.ImageIndex = 0;
					item.Tag = post;
					listView1.Items.Add(item);
				}
				listView1.EndUpdate();

			} catch {
				MessageBox.Show(Resources.CouldNotRetrievePostList);
				DialogResult = DialogResult.Cancel;
				Close();
			} finally {
				Cursor.Current = Cursors.Default;
			}
		}

		private void closeMenu_Click(object sender, EventArgs e) {
			DialogResult = DialogResult.Cancel;
			Close();
		}

		private void selectMenu_Click(object sender, EventArgs e) {
			listView1_ItemActivate(sender, e);
		}

		private void deleteMenu_Click(object sender, EventArgs e) {
			BlogPost post=GetSelectedPost();
			DeletePost(post);
			listView1.Items.RemoveAt(listView1.SelectedIndices[0]);
		}

		private void DeletePost(BlogPost post) {
			Manager.DeletePost(post);
		}
		private ListViewItem GetSelectedItem() {
			return listView1.Items[listView1.SelectedIndices[0]];
		}
		private BlogPost GetSelectedPost() {
			ListViewItem actived = GetSelectedItem();
			return (BlogPost)actived.Tag;
		}
	}
}